package com.autonavi.abs.common.aop.aspect;

import com.alibaba.fastjson.JSON;
import com.autonavi.abs.common.api.ServiceResponse;
import com.autonavi.abs.common.exception.MessageException;
import com.autonavi.abs.common.util.LogUtils;
import com.google.common.collect.Lists;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author tianquan.ld
 * @version V1.0
 * <p>Description: HSF日志打印、异常处理
 * </p>
 * @date 2020-07-10 19:52
 */
@Component
@Aspect
public class HsfHandlerAspect {

    private final static Logger LOGGER = LoggerFactory.getLogger(HsfHandlerAspect.class);

    @Around(value = "@annotation(com.autonavi.abs.common.aop.annotation.HsfHandler)")
    public Object around(ProceedingJoinPoint jp) throws Throwable {

        long start = System.currentTimeMillis();

        String clazz = jp.getSignature().getDeclaringType().getSimpleName();
        String method = jp.getSignature().getName();

        List<String> paramJsonList = Lists.newArrayList();
        try {
            // 请求日志
            paramJsonList = LogUtils.getValidListJson(jp.getArgs());
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }

        String paramJson = JSON.toJSONString(paramJsonList);
        LOGGER.info("{}.{},start:{},param:{}", clazz, method, start, paramJson);

        Object result = null;
        try {
            result = jp.proceed();
        } catch (MessageException e) {
            LOGGER.error("{}.{},start:{},param:{},error:{}", clazz, method, start, paramJson, e.getMessage());
            return ServiceResponse.serverError(e.getMessage());
        } catch (Exception e) {
            LOGGER.error("{}.{},start:{},param:{},error:{}", clazz, method, start, paramJson, e.getMessage());
            return ServiceResponse.serverError();
        }

        // 返回值日志
        long end = System.currentTimeMillis();
        long cost = end - start;
        LOGGER.info("{}.{},start:{},end:{},cost:{},param:{},result:{}"
                , clazz, method, start, end, cost, paramJson, JSON.toJSONString(result));

        // 返回处理结果
        return result;
    }


}
